package com.timedomain.him.remake.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;

import com.timedomain.him.remake.R;
import com.timedomain.him.remake.core.ChannelCreator;
import com.timedomain.him.remake.core.SimplePlayer;
import com.timedomain.him.remake.models.MorningCall;
import com.timedomain.him.remake.ui.common.CallingActivity;
import com.timedomain.him.remake.utils.*;

import org.jetbrains.annotations.Nullable;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WelcomeActivity extends BaseActivity {

    private LinearLayout page4;
    private LinearLayout page3;
    private LinearLayout page2;
    private LinearLayout page1;
    private LinearLayout panWelcomeLengao;
    private Button btnWelcomeLengao;
    private LinearLayout panWelcomeChenjing;
    private Button btnWelcomeChenjing;
    private LinearLayout panWelcomeWennuan;
    private Button btnWelcomeWennuan;
    private LinearLayout panWelcomeRelie;
    private Button btnWelcomeRelie;


    private void initUI(){
        page4 = (LinearLayout)findViewById(R.id.page4);
        page3 = (LinearLayout)findViewById(R.id.page3);
        page2 = (LinearLayout)findViewById(R.id.page2);
        page1 = (LinearLayout)findViewById(R.id.page1);
        panWelcomeLengao = (LinearLayout)findViewById(R.id.panWelcomeLengao);
        btnWelcomeLengao = (Button)findViewById(R.id.btnWelcomeLengao);
        panWelcomeChenjing = (LinearLayout)findViewById(R.id.panWelcomeChenjing);
        btnWelcomeChenjing = (Button)findViewById(R.id.btnWelcomeChenjing);
        panWelcomeWennuan = (LinearLayout)findViewById(R.id.panWelcomeWennuan);
        btnWelcomeWennuan = (Button)findViewById(R.id.btnWelcomeWennuan);
        panWelcomeRelie = (LinearLayout)findViewById(R.id.panWelcomeRelie);
        btnWelcomeRelie = (Button)findViewById(R.id.btnWelcomeRelie);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        initUI();
        page1.setVisibility(View.VISIBLE);
        page1.startAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
    }

    public void gotoPage2(View view) {
        Animation anim2 = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
        anim2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                page1.setVisibility(View.GONE);
                page2.setVisibility(View.VISIBLE);
                page2.startAnimation(AnimationUtils.loadAnimation(WelcomeActivity.this,android.R.anim.fade_in));
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        page1.startAnimation(anim2);
    }


    SimplePlayer mplayer = null;

    private void playAudio(String path){
        if(mplayer != null){
            mplayer.stop();
            mplayer.close();
            mplayer = null;
        }
        if(path != null){
            mplayer = new SimplePlayer(ChannelCreator.FromFile(this,path));
            mplayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        playAudio(null);
    }

    public void btnPreviewRelie(View view) {
        btnWelcomeRelie.setVisibility(View.VISIBLE);
        panWelcomeRelie.setVisibility(View.GONE);
        btnWelcomeWennuan.setVisibility(View.VISIBLE);
        panWelcomeWennuan.setVisibility(View.GONE);
        btnWelcomeChenjing.setVisibility(View.VISIBLE);
        panWelcomeChenjing.setVisibility(View.GONE);
        btnWelcomeLengao.setVisibility(View.VISIBLE);
        panWelcomeLengao.setVisibility(View.GONE);


        btnWelcomeRelie.setVisibility(View.GONE);
        panWelcomeRelie.setVisibility(View.VISIBLE);
        playAudio(FileUtils.pathCombine("demo","stage1","relie.ogg"));
    }

    public void btnPreviewWennuan(View view) {
        btnWelcomeRelie.setVisibility(View.VISIBLE);
        panWelcomeRelie.setVisibility(View.GONE);
        btnWelcomeWennuan.setVisibility(View.VISIBLE);
        panWelcomeWennuan.setVisibility(View.GONE);
        btnWelcomeChenjing.setVisibility(View.VISIBLE);
        panWelcomeChenjing.setVisibility(View.GONE);
        btnWelcomeLengao.setVisibility(View.VISIBLE);
        panWelcomeLengao.setVisibility(View.GONE);


        btnWelcomeWennuan.setVisibility(View.GONE);
        panWelcomeWennuan.setVisibility(View.VISIBLE);
        playAudio(FileUtils.pathCombine("demo","stage1","wennuan.ogg"));
    }

    public void btnPreviewChenjing(View view) {
        btnWelcomeRelie.setVisibility(View.VISIBLE);
        panWelcomeRelie.setVisibility(View.GONE);
        btnWelcomeWennuan.setVisibility(View.VISIBLE);
        panWelcomeWennuan.setVisibility(View.GONE);
        btnWelcomeChenjing.setVisibility(View.VISIBLE);
        panWelcomeChenjing.setVisibility(View.GONE);
        btnWelcomeLengao.setVisibility(View.VISIBLE);
        panWelcomeLengao.setVisibility(View.GONE);


        btnWelcomeChenjing.setVisibility(View.GONE);
        panWelcomeChenjing.setVisibility(View.VISIBLE);
        playAudio(FileUtils.pathCombine("demo","stage1","chenjing.ogg"));
    }

    public void btnPreviewLengao(View view) {
        btnWelcomeRelie.setVisibility(View.VISIBLE);
        panWelcomeRelie.setVisibility(View.GONE);
        btnWelcomeWennuan.setVisibility(View.VISIBLE);
        panWelcomeWennuan.setVisibility(View.GONE);
        btnWelcomeChenjing.setVisibility(View.VISIBLE);
        panWelcomeChenjing.setVisibility(View.GONE);
        btnWelcomeLengao.setVisibility(View.VISIBLE);
        panWelcomeLengao.setVisibility(View.GONE);


        btnWelcomeLengao.setVisibility(View.GONE);
        panWelcomeLengao.setVisibility(View.VISIBLE);
        playAudio(FileUtils.pathCombine("demo","stage1","lengao.ogg"));
    }



    public void gotoPage3(View view) {
        playAudio(null);
        Animation anim2 = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
        anim2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                page2.setVisibility(View.GONE);
                page3.setVisibility(View.VISIBLE);
                page3.startAnimation(AnimationUtils.loadAnimation(WelcomeActivity.this,android.R.anim.fade_in));
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        page2.startAnimation(anim2);
    }

    public void btnPreviewClick(View view) {
        playAudio(FileUtils.pathCombine("demo","stage2",view.getTag().toString()+".ogg"));
    }

    public void gotoPage4(View view) {

        playAudio(null);
        Animation anim2 = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
        anim2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                page3.setVisibility(View.GONE);
                page4.setVisibility(View.VISIBLE);
                page4.startAnimation(AnimationUtils.loadAnimation(WelcomeActivity.this,android.R.anim.fade_in));
                setTimeout(WelcomeActivity.this::startFirstCall,5000);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        page3.startAnimation(anim2);
    }

    public void startFirstCall(){
        DB.MorningCall.Add(MorningCall.createForPath(this,FileUtils.pathCombine("morningcall", "initial/初次见面.ogg")));
        AppSettings.firstRun = false;
        AppSettings.saveSettings(this);
        CallingActivity.startNewCall(this,FileUtils.pathCombine("morningcall", "initial/初次见面.ogg"),false);
        startedFirstCall = true;
    }

    boolean startedFirstCall = false;

    @Override
    protected void onResume() {
        super.onResume();
        if(startedFirstCall){
            startActivity(new Intent(this,MainActivity.class));
            finish();
        }
    }


    private static final int READ_REQUEST_CODE = 721;
    
    public void loadSaveFile(View view) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(intent, READ_REQUEST_CODE);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == READ_REQUEST_CODE && resultCode == RESULT_OK){
            Uri uri = data.getData();
            RunUtils.runProgressDialog(this,"正在读取数据...",()->{
                try {
                    String text = PhysicalFileUtils.readAllText(getContentResolver().openInputStream(uri));
                    BackupRestoreUtils.BackupDataHolder backupData = BackupRestoreUtils.getData(text);
                    runOnUiThread(()->{
                        new AlertDialog.Builder(this).setTitle("读取存档：")
                                .setMessage("是否读取这个存档？\n\n创建设备："+backupData.backupUserName+"\n创建时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(backupData.backupTime)))
                                .setPositiveButton("读取",(dialog,which)->{

                                    RunUtils.runProgressDialog(this,"正在恢复数据",()->{

                                        try {
                                            BackupRestoreUtils.restoreData(this,backupData);
                                            runOnUiThread(()->{
                                                startActivity(new Intent(this,SplashActivity.class));
                                                finish();
                                            });
                                        } catch (BackupRestoreUtils.BackupIncompatibleException e) {
                                            runOnUiThread(()->{
                                                new AlertDialog.Builder(this).setTitle("读取存档出错").setMessage(e.getMessage())
                                                        .setNegativeButton(android.R.string.ok,null).setCancelable(false).create().show();
                                            });
                                        }catch (Exception e) {
                                            e.printStackTrace();
                                            runOnUiThread(()->showToast("恢复存档出错，请清除APP数据后重试"));
                                        }


                                    });


                                }).setNegativeButton(android.R.string.cancel,null)
                                .setCancelable(true).create().show();

                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("读取存档失败：文件异常");
                }
            });
        }
    }
}
